from numpy import *
import svdRec

#numpy有了内置的奇异值分解矩阵方法
U, Sigma ,VT = linalg.svd([[1,1],[7,7]])
print('U \n', U)
print('Sigma\n' , Sigma)
print('VT\n',VT)
#########################新的一个例子#############
Data = svdRec.loadExData()
U, Sigma ,VT = linalg.svd(Data)
print('U \n', U)
print('Sigma\n' , Sigma)
print('VT\n',VT)
#由于Sig3是个矩阵，所以要转换一下
Sig3 = mat([[Sigma[0],0,0],[0,Sigma[1],0],[0,0,Sigma[2]]])
print('Sig3\n',Sig3)
#将分解的三个奇异值矩阵合并回来
print('U[:,:3] * Sig3 *VT[:3,:]\n',U[:,:3] * Sig3 *VT[:3,:])



###########推荐过程，给定一个用户，系统会为此返回N个最好的推荐菜。###############
myMat = mat(svdRec.loadExData())
myMat[0,1] = myMat[0,0] = myMat[1,0] = myMat[2,0] = 4
myMat[3,3] =2
print('myMat\n',myMat)
#对用户2进行了评分得出推荐菜
recomList = svdRec.recommend(myMat ,2)
print('COS recomList\n', recomList)
recomList = svdRec.recommend(myMat,2,simMeas = svdRec.ecludSim)
print('ECLU recomList\n', recomList)
recomList = svdRec.recommend(myMat,2,simMeas = svdRec.pearsSim)
print('PEARS recomList\n', recomList)

###########利用SVD提高推荐的效果################
myMat = mat(svdRec.loadExData2())
U, Sigma ,VT = linalg.svd(myMat)
print('Sigma\n',Sigma)
Sig2 = Sigma **2
#总能量
sum(Sig2)
#总能量的90%
sum(Sig2) * 0.9
#前三个元素高于总能量的90%，所以认为可以将1个11维的函数转化为3维
sum(Sig2[:3])
#这里的1的意思是推荐给1号用户的菜系
recomList = svdRec.recommend(myMat ,1, estMethod = svdRec.svdEst) 
print('recomList svd\n',recomList)

##############利用SVD进行图像压缩###################
svdRec.imgCompress(2)




